<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { Button } from "../components/ui/button";
import { ScrollArea } from "../components/ui/scroll-area";
import {
  Tabs,
  TabsList,
  TabsTrigger,
  TabsContent,
} from "../components/ui/tabs";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
} from "../components/ui/select";
import { Switch } from "../components/ui/switch";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Badge } from "../components/ui/badge";
import {
  SUPPORTED_FORMATS,
  simulateConversion,
  calculateTotalCompression,
  formatFileSize,
  type ConversionSettings,
  type ConversionResult,
  calculateConvertedSize,
  convertImageFormat, // 新增真正的格式转换函数
  sanitizeFileName, // 新增文件名清理函数
} from "../utils/imageConverter";
import { useUpload } from "@/composables/useUpload";
import { toast } from "vue-sonner";

const tab = ref("upload");
const fileInput = ref<HTMLInputElement | null>(null);
const autoConvert = ref(true);
const defaultFormat = ref("WEBP");
const quality = ref(85);
const resizeEnabled = ref(false);
const maxWidth = ref(1920);
const maxHeight = ref(1080);

interface UploadItem {
  id: string;
  url: string;
  name: string;
  size: number;
  sizeLabel: string;
  type: string;
  typeLabel: string;
  targetFormat: string;
  status: "pending" | "uploading" | "converting" | "done";
  progress: number;
  originalSize: number;
  convertedSize?: number;
  convertedSizeLabel?: string;
  conversionResult?: ConversionResult;
  file: File; // 新增 file 字段
}

const queue = ref<UploadItem[]>([]);

const {
  uploadBatch,
  isUploading,
  uploadProgress,
  uploadError,
  uploadState,
  resetUploadState,
} = useUpload();

function onFileChange(e: Event) {
  const files = (e.target as HTMLInputElement).files;
  if (files && files.length) {
    addFiles(Array.from(files));
    if (fileInput.value) fileInput.value.value = "";
  }
}

function onDrop(e: DragEvent) {
  const files = e.dataTransfer?.files;
  if (files && files.length) {
    addFiles(Array.from(files));
  }
}

function addFiles(files: File[]) {
  for (const file of files) {
    const id = Math.random().toString(36).slice(2, 10);
    const ext = file.name.split(".").pop()?.toUpperCase() || "";
    const typeLabel = file.type ? file.type : ext;
    const sizeLabel = formatFileSize(file.size);
    let convertedSize: number | undefined = undefined;
    let convertedSizeLabel: string | undefined = undefined;
    let conversionResult: ConversionResult | undefined = undefined;
    if (autoConvert.value) {
      // 计算转换后大小
      const settings: ConversionSettings = {
        quality: quality.value,
        resizeEnabled: resizeEnabled.value,
        maxWidth: maxWidth.value,
        maxHeight: maxHeight.value,
      };
      conversionResult = calculateConvertedSize(
        file.size,
        defaultFormat.value,
        settings
      );
      convertedSize = conversionResult.convertedSize;
      convertedSizeLabel = formatFileSize(convertedSize);
    }
    queue.value.push({
      id,
      url: URL.createObjectURL(file),
      name: file.name,
      size: file.size,
      sizeLabel,
      type: file.type,
      typeLabel,
      targetFormat: autoConvert.value ? defaultFormat.value : ext,
      status: "pending",
      progress: 0,
      originalSize: file.size,
      convertedSize,
      convertedSizeLabel,
      conversionResult,
      file, // 新增 file 字段
    });
  }
}

function removeItem(id: string) {
  queue.value = queue.value.filter(i => i.id !== id);
}

// 修正类型声明
async function uploadSingleWithProgress(item: UploadItem): Promise<void> {
  try {
    // 如果启用了自动转换，先进行格式转换
    if (
      autoConvert.value &&
      item.targetFormat !== item.typeLabel.split("/").pop()?.toUpperCase()
    ) {
      item.status = "converting";
      item.progress = 0;

      const settings: ConversionSettings = {
        quality: quality.value,
        resizeEnabled: resizeEnabled.value,
        maxWidth: maxWidth.value,
        maxHeight: maxHeight.value,
      };

      // 进行真正的格式转换
      const convertedFile = await convertImageFormat(
        item.file,
        item.targetFormat,
        settings,
        progress => {
          item.progress = progress;
        }
      );

      // 更新文件信息
      item.file = convertedFile;
      item.size = convertedFile.size;
      item.sizeLabel = formatFileSize(convertedFile.size);
      item.type = convertedFile.type;
      item.typeLabel = convertedFile.type;

      // 更新转换后的大小信息
      if (item.conversionResult) {
        item.conversionResult.convertedSize = convertedFile.size;
        item.convertedSize = convertedFile.size;
        item.convertedSizeLabel = formatFileSize(convertedFile.size);
      }
    }

    // 开始上传
    item.status = "uploading";
    item.progress = 0;

    // 清理文件名，确保符合存储服务要求
    const originalName = item.file.name;
    const sanitizedName = sanitizeFileName(originalName);

    // 如果文件名被修改，创建新的 File 对象
    let fileToUpload = item.file;
    if (sanitizedName !== originalName) {
      fileToUpload = new File([item.file], sanitizedName, {
        type: item.file.type,
        lastModified: item.file.lastModified,
      });
      console.log("文件名已清理:", {
        original: originalName,
        sanitized: sanitizedName,
      });
    }

    const formData = new FormData();
    formData.append("file", fileToUpload);

    // 调试信息：检查文件名
    console.log("上传文件信息:", {
      fileName: fileToUpload.name,
      fileSize: fileToUpload.size,
      fileType: fileToUpload.type,
      hasName: !!fileToUpload.name,
      nameLength: fileToUpload.name.length,
    });

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://123.57.214.94:9000/api/upload/single");
    xhr.setRequestHeader("User", "1");
    xhr.upload.onprogress = event => {
      if (event.lengthComputable) {
        // 如果进行了转换，上传进度从50%开始
        const uploadProgress = Math.round((event.loaded / event.total) * 50);
        item.progress = 50 + uploadProgress;
      }
    };
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        item.progress = 100;
        item.status = "done";
        // 可解析后端返回的 url/size 等信息
      } else {
        item.status = "pending";
        item.progress = 0;
        toast("上传失败", {
          description: item.name + " 上传失败",
        });
        throw new Error("上传失败");
      }
    };
    xhr.onerror = () => {
      item.status = "pending";
      item.progress = 0;
      toast("上传失败", { description: item.name + " 上传失败" });
      throw new Error("上传失败");
    };
    xhr.send(formData);
  } catch (error) {
    item.status = "pending";
    item.progress = 0;
    throw error;
  }
}

async function startUpload() {
  const pendingItems = queue.value.filter(item => item.status === "pending");
  if (pendingItems.length === 0) return;

  for (const item of pendingItems) {
    try {
      await uploadSingleWithProgress(item);
    } catch (e) {
      // 错误已在 uploadSingleWithProgress 里处理
    }
  }
}

function clearDone() {
  queue.value = queue.value.filter(i => i.status !== "done");
}

const pendingCount = computed(
  () => queue.value.filter(i => i.status === "pending").length
);
const uploadingCount = computed(
  () => queue.value.filter(i => i.status === "uploading").length
);
const convertingCount = computed(
  () => queue.value.filter(i => i.status === "converting").length
);
const doneCount = computed(
  () => queue.value.filter(i => i.status === "done").length
);

// 计算总压缩率
const totalCompression = computed(() => {
  const doneItems = queue.value.filter(i => i.status === "done");
  if (doneItems.length === 0) return 0;

  const results = doneItems
    .map(item => item.conversionResult)
    .filter((result): result is ConversionResult => result !== undefined);

  return calculateTotalCompression(results);
});

// 计算队列总大小
const totalQueueSize = computed(() => {
  return queue.value.reduce((sum, item) => sum + item.originalSize, 0);
});
</script>

<template>
  <main class="h-full max-w-6xl mx-auto px-6">
    <!-- 顶部统计 -->
    <div class="mb-4">
      <div class="flex justify-start items-start gap-2">
        <div class="w-2 bg-yellow-200 h-8"></div>
        <div class="text-2xl font-bold">图片上传与处理</div>
      </div>
    </div>
    <!-- Tabs -->
    <Tabs v-model="tab" class="flex-1 mb-6">
      <TabsList class="w-full bg-gray-100 rounded-full p-1 flex">
        <TabsTrigger value="upload" class="flex-1">批量上传</TabsTrigger>
        <TabsTrigger value="setting" class="flex-1">格式设置</TabsTrigger>
      </TabsList>
      <Transition name="fade-slide" mode="out-in">
        <template #default>
          <TabsContent v-if="tab === 'upload'" value="upload" key="upload">
            <!-- 上传区 -->
            <div class="bg-white rounded-xl border p-6 mb-4">
              <div
                class="border-2 border-dashed rounded-lg flex flex-col items-center justify-center py-10 cursor-pointer hover:border-primary transition relative"
                @drop.prevent="onDrop"
                @dragover.prevent
                @click="fileInput?.click()"
              >
                <input
                  ref="fileInput"
                  type="file"
                  multiple
                  accept="image/*"
                  class="hidden"
                  @change="onFileChange"
                />
                <div class="flex flex-col items-center gap-2">
                  <svg
                    t="1753018963615"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="1689"
                    width="150"
                    height="150"
                  >
                    <path
                      d="M391.168 571.392l11.776-11.776V432.128c0-11.264 4.096-21.504 10.752-29.696L445.44 363.52c6.144-7.68 15.872-12.8 26.624-12.8h249.344c-1.536-2.048-2.56-4.608-4.608-6.144l-32.256-38.912c-6.656-7.68-16.384-12.8-27.136-12.8H379.392c-10.752 0-20.48 5.12-26.624 12.8l-32.256 38.912c-6.656 8.192-10.752 18.432-10.752 29.696v290.304c0 25.6 20.992 46.592 46.592 46.592h46.592v-139.264h-11.776z m-13.312-255.488h278.528l21.504 23.04H358.912l18.944-23.04z"
                      fill="#FFCB99"
                      p-id="1690"
                    ></path>
                    <path
                      d="M452.096 397.312h275.456V373.76H471.04zM594.432 519.168l52.224 52.224h-81.408V710.656h92.672v-81.408h69.632v-11.776L611.84 501.76z"
                      fill="#FFCB99"
                      p-id="1691"
                    ></path>
                    <path
                      d="M657.92 710.656h23.04c25.6 0 46.592-20.992 46.592-46.592v-34.816h-69.632v81.408z"
                      fill="#FF7E00"
                      p-id="1692"
                    ></path>
                    <path
                      d="M809.984 402.432l-32.256-38.912c-6.656-7.68-16.384-12.8-27.136-12.8H472.064c-10.752 0-20.48 5.12-26.624 12.8l-32.256 38.912c-6.656 8.192-10.752 18.432-10.752 29.696V722.432c0 25.6 20.992 46.592 46.592 46.592h325.12c25.6 0 46.592-20.992 46.592-46.592V432.128c0-11.264-4.096-21.504-10.752-29.696z m-82.432 226.816v34.816c0 25.6-20.992 46.592-46.592 46.592h-115.712V629.76H483.84l110.08-110.08 17.408-17.408 116.224 116.224 11.776 11.776h-11.776z m0-231.936H452.096L471.04 373.76h278.528l21.504 23.04h-43.52z"
                      fill="#FF7E00"
                      p-id="1693"
                    ></path>
                    <path
                      d="M226.304 553.984h-29.696v-29.696c0-6.656-5.12-11.776-11.776-11.776s-11.776 5.12-11.776 11.776v29.696H143.36c-6.656 0-11.776 5.12-11.776 11.776s5.12 11.776 11.776 11.776h29.696v29.696c0 6.656 5.12 11.776 11.776 11.776s11.776-5.12 11.776-11.776v-29.696h29.696c6.656 0 11.776-5.12 11.776-11.776s-5.12-11.776-11.776-11.776zM811.52 195.584c14.848 14.848 10.24 33.792 6.656 47.616-3.584 13.824-4.096 20.48 0.512 25.6 5.12 5.12 11.264 4.096 25.6 0.512 13.824-3.584 32.768-8.192 47.616 6.656 14.848 14.848 10.24 33.28 6.656 47.104-3.584 13.824-4.608 20.48 0.512 25.6 4.608 4.608 4.608 11.776 0 16.384-4.608 4.608-11.776 4.608-16.384 0-14.848-14.848-10.24-33.28-6.656-47.104 3.584-13.824 4.608-20.48-0.512-25.6s-11.264-4.096-25.6-0.512c-13.824 3.584-32.768 8.192-47.104-6.656-14.848-14.848-10.24-33.792-6.656-47.616 3.584-13.824 4.608-20.48-0.512-25.6s-11.776-4.096-25.6-0.512c-13.824 3.584-32.768 8.192-47.616-6.656-4.608-4.608-4.608-11.776 0-16.384 4.608-4.608 11.776-4.608 16.384 0 5.12 5.12 11.264 4.096 25.6 0.512 13.312-3.072 32.256-7.68 47.104 6.656z"
                      fill="#FFC879"
                      p-id="1694"
                    ></path>
                    <path
                      d="M878.08 652.8h65.536v65.536h-65.536zM230.4 386.048l34.816-35.328H195.584z"
                      fill="#FFF7EC"
                      p-id="1695"
                    ></path>
                    <path
                      d="M330.752 773.12l-49.664-49.664c-3.584-3.584-9.216-3.584-12.8 0l-49.664 49.664c-3.584 3.584-3.584 9.216 0 12.8l49.664 49.664c3.584 3.584 9.216 3.584 12.8 0l49.664-49.664c3.584-3.072 3.584-9.216 0-12.8z m-56.32 43.52l-36.864-36.864 36.864-36.864 36.864 36.864-36.864 36.864z"
                      fill="#FFC879"
                      p-id="1696"
                    ></path>
                  </svg>
                  <div class="text-gray-500">拖拽文件到此处或点击选择</div>
                  <div class="text-xs text-gray-400">
                    支持 JPG、PNG、WebP、AVIF 等格式，单次最多上传50张图片
                  </div>
                  <!-- <Button class="mt-2" @click.stop="fileInput?.click()"
                    ><svg
                      class="w-4 h-4 mr-1"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M4 4v16c0 1.1.9 2 2 2h12a2 2 0 002-2V4"
                      />
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 16v-8m0 0l-4 4m4-4l4 4"
                      /></svg
                    >选择文件</Button
                  > -->
                </div>
              </div>
            </div>
            <!-- 上传操作按钮 -->
            <div class="flex gap-2 mb-4 items-center">
              <Button
                :disabled="isUploading || !pendingCount"
                @click="startUpload"
                class="h-8"
                >开始上传 ({{ pendingCount }})</Button
              >
              <Button
                variant="outline"
                :disabled="!doneCount"
                @click="clearDone"
                class="h-8"
                >清理已完成 ({{ doneCount }})</Button
              >
              <div class="flex gap-2 items-center">
                <Badge variant="outline" class="text-xs">
                  待处理: {{ pendingCount }}
                </Badge>
                <Badge variant="outline" class="text-xs">
                  上传中: {{ uploadingCount }}
                </Badge>
                <Badge variant="outline" class="text-xs">
                  转换中: {{ convertingCount }}
                </Badge>
                <Badge variant="outline" class="text-xs">
                  已完成: {{ doneCount }}
                </Badge>
                <Badge
                  v-if="totalCompression > 0"
                  variant="default"
                  class="text-xs bg-green-100 text-green-700 hover:bg-green-100"
                >
                  压缩率: {{ totalCompression }}%
                </Badge>
                <Badge
                  v-if="totalQueueSize > 0"
                  variant="secondary"
                  class="text-xs"
                >
                  总大小: {{ formatFileSize(totalQueueSize) }}
                </Badge>
              </div>
            </div>
            <!-- 上传进度条和错误提示 -->
            <div v-if="isUploading" class="mb-2">
              <div class="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                <div
                  class="h-2 bg-primary rounded-full transition-all duration-300"
                  :style="{ width: uploadProgress + '%' }"
                ></div>
              </div>
            </div>

            <!-- 上传队列 -->
            <div v-if="queue.length" class="bg-white rounded-xl border p-4">
              <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-2">
                  <span class="font-medium">上传队列</span>
                  <Badge variant="secondary" class="text-xs">
                    {{ queue.length }} 个文件
                  </Badge>
                  <Badge variant="outline" class="text-xs">
                    {{ formatFileSize(totalQueueSize) }}
                  </Badge>
                </div>
              </div>
              <ScrollArea class="h-[200px]">
                <TransitionGroup
                  name="queue-fade"
                  tag="div"
                  class="pr-4 space-y-3"
                >
                  <div
                    v-for="item in queue"
                    :key="item.id"
                    class="relative p-3 bg-gray-50 rounded-lg border hover:bg-gray-100 transition-colors"
                  >
                    <div class="flex items-start gap-4">
                      <img
                        :src="item.url"
                        class="w-16 h-16 object-cover rounded-lg border flex-shrink-0"
                      />
                      <div class="flex-1 min-w-0">
                        <div class="flex items-center justify-between mb-4">
                          <div class="truncate text-sm font-medium">
                            {{ item.name }}
                          </div>
                          <Button
                            size="icon"
                            variant="ghost"
                            class="size-6 flex-shrink-0 hover:bg-gray-200"
                            @click="removeItem(item.id)"
                          >
                            <svg
                              class="w-4 h-4"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M6 18L18 6M6 6l12 12"
                              />
                            </svg>
                          </Button>
                        </div>
                        <div
                          class="text-xs text-gray-500 flex gap-3 items-center mb-3"
                        >
                          <span>{{ item.sizeLabel }}</span>
                          <span
                            v-if="item.convertedSizeLabel"
                            class="text-green-600"
                          >
                            → {{ item.convertedSizeLabel }}
                          </span>
                          <span>{{ item.typeLabel }}</span>
                          <Badge
                            v-if="item.status === 'done'"
                            variant="default"
                            class="text-xs bg-green-100 text-green-700 hover:bg-green-100"
                          >
                            已完成
                          </Badge>
                          <Badge
                            v-else-if="item.status === 'uploading'"
                            variant="default"
                            class="text-xs bg-blue-100 text-blue-700 hover:bg-blue-100"
                          >
                            上传中
                          </Badge>
                          <Badge
                            v-else-if="item.status === 'converting'"
                            variant="default"
                            class="text-xs bg-orange-100 text-orange-700 hover:bg-orange-100"
                          >
                            转换中
                          </Badge>
                          <Badge v-else variant="secondary" class="text-xs">
                            待处理
                          </Badge>
                        </div>
                        <div class="flex items-center gap-3">
                          <div
                            v-if="item.status !== 'pending'"
                            class="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden"
                          >
                            <div
                              class="h-2 bg-primary rounded-full transition-all duration-300"
                              :style="{ width: item.progress + '%' }"
                            ></div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 格式选择框 - 右下角 -->
                    <div class="absolute bottom-6 right-3">
                      <Select
                        v-model="item.targetFormat"
                        class="w-24 h-14"
                        :disabled="item.status !== 'pending'"
                      >
                        <SelectTrigger class="h-8">
                          <span class="text-xs">{{
                            SUPPORTED_FORMATS.find(
                              f => f.value === item.targetFormat
                            )?.label || item.targetFormat
                          }}</span>
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem
                            v-for="fmt in SUPPORTED_FORMATS"
                            :key="fmt.value"
                            :value="fmt.value"
                          >
                            <div
                              class="flex items-center justify-between w-full"
                            >
                              <span>{{ fmt.label }}</span>
                              <span class="text-xs text-gray-500">{{
                                fmt.compression
                              }}</span>
                            </div>
                          </SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </TransitionGroup>
              </ScrollArea>
            </div>
          </TabsContent>
          <TabsContent v-else value="setting" key="setting">
            <div class="bg-white rounded-xl border p-6 my-3">
              <div class="font-medium mb-4">支持的格式</div>
              <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div
                  v-for="fmt in SUPPORTED_FORMATS"
                  :key="fmt.value"
                  class="rounded-lg border p-4 flex flex-col gap-2"
                >
                  <div class="flex items-center justify-between">
                    <div class="font-bold">{{ fmt.label }}</div>
                    <div
                      class="text-xs px-2 py-1 rounded-full"
                      :class="{
                        'bg-red-100 text-red-700': fmt.compression === '极高',
                        'bg-orange-100 text-orange-700':
                          fmt.compression === '高',
                        'bg-yellow-100 text-yellow-700':
                          fmt.compression === '中',
                        'bg-green-100 text-green-700': fmt.compression === '低',
                      }"
                    >
                      {{ fmt.compression }}压缩
                    </div>
                  </div>
                  <div class="text-xs text-gray-500">{{ fmt.desc }}</div>
                </div>
              </div>
            </div>

            <div class="bg-white rounded-xl border p-6 mb-4">
              <div class="flex items-center gap-3 mb-4">
                <svg
                  class="w-5 h-5 text-gray-500"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 8v4l3 3"
                  />
                  <circle cx="12" cy="12" r="10" />
                </svg>
                <span class="font-medium">自动转换设置</span>
              </div>

              <div class="space-y-4">
                <div class="flex items-center gap-3">
                  <input
                    type="checkbox"
                    :checked="autoConvert"
                    @change="
                      autoConvert = ($event.target as HTMLInputElement).checked
                    "
                    class="w-4 h-4"
                  />
                  <span>启用自动格式转换</span>
                  <span class="text-xs text-gray-500">({{ autoConvert }})</span>
                </div>

                <div
                  v-if="autoConvert"
                  class="space-y-4 p-4 bg-gray-50 rounded-lg border"
                >
                  <!-- 调试信息 -->
                  <div class="text-xs text-gray-500 mb-2">
                    自动转换状态: {{ autoConvert ? "已启用" : "已禁用" }} ({{
                      autoConvert
                    }})
                  </div>
                  <div class="space-y-3">
                    <Label for="defaultFormat">默认转换格式</Label>
                    <Select v-model="defaultFormat">
                      <SelectTrigger class="w-full">
                        <span>{{
                          SUPPORTED_FORMATS.find(f => f.value === defaultFormat)
                            ?.label
                        }}</span>
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem
                          v-for="fmt in SUPPORTED_FORMATS"
                          :key="fmt.value"
                          :value="fmt.value"
                        >
                          <div class="flex items-center justify-between w-full">
                            <span>{{ fmt.label }}</span>
                            <span class="text-xs text-gray-500"
                              >{{ fmt.compression }}压缩</span
                            >
                          </div>
                        </SelectItem>
                      </SelectContent>
                    </Select>
                    <div class="text-xs text-gray-500">
                      新上传的文件将自动转换为
                      {{
                        SUPPORTED_FORMATS.find(f => f.value === defaultFormat)
                          ?.label
                      }}
                      格式
                    </div>
                  </div>

                  <div class="space-y-2">
                    <div class="text-sm font-medium">格式说明</div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                      <div
                        v-for="fmt in SUPPORTED_FORMATS"
                        :key="fmt.value"
                        class="flex items-center gap-2 p-2 rounded border"
                        :class="{
                          'bg-primary/10 border-primary':
                            fmt.value === defaultFormat,
                          'bg-white': fmt.value !== defaultFormat,
                        }"
                      >
                        <div
                          class="w-3 h-3 rounded-full"
                          :class="{
                            'bg-primary': fmt.value === defaultFormat,
                            'bg-gray-300': fmt.value !== defaultFormat,
                          }"
                        ></div>
                        <div class="flex-1">
                          <div class="text-sm font-medium">{{ fmt.label }}</div>
                          <div class="text-xs text-gray-500">
                            {{ fmt.desc }}
                          </div>
                        </div>
                        <div
                          class="text-xs px-2 py-1 rounded-full"
                          :class="{
                            'bg-red-100 text-red-700':
                              fmt.compression === '极高',
                            'bg-orange-100 text-orange-700':
                              fmt.compression === '高',
                            'bg-yellow-100 text-yellow-700':
                              fmt.compression === '中',
                            'bg-green-100 text-green-700':
                              fmt.compression === '低',
                          }"
                        >
                          {{ fmt.compression }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div class="space-y-3">
                    <Label for="quality">图片质量</Label>
                    <div class="flex items-center gap-3">
                      <Input
                        id="quality"
                        v-model="quality"
                        type="number"
                        min="1"
                        max="100"
                        class="w-20"
                      />
                      <span class="text-sm text-gray-500">% (1-100)</span>
                    </div>
                    <div class="text-xs text-gray-500">
                      质量越高，文件越大，但图片更清晰
                    </div>
                  </div>

                  <div class="space-y-3">
                    <div class="flex items-center gap-3">
                      <input
                        type="checkbox"
                        :checked="resizeEnabled"
                        @change="
                          resizeEnabled = ($event.target as HTMLInputElement)
                            .checked
                        "
                        class="w-4 h-4"
                      />
                      <Label for="resize">启用尺寸调整</Label>
                    </div>
                    <div v-if="resizeEnabled" class="grid grid-cols-2 gap-3">
                      <div>
                        <Label for="maxWidth" class="text-xs">最大宽度</Label>
                        <Input
                          id="maxWidth"
                          v-model="maxWidth"
                          type="number"
                          class="w-full"
                        />
                      </div>
                      <div>
                        <Label for="maxHeight" class="text-xs">最大高度</Label>
                        <Input
                          id="maxHeight"
                          v-model="maxHeight"
                          type="number"
                          class="w-full"
                        />
                      </div>
                    </div>
                    <div class="text-xs text-gray-500">
                      超过此尺寸的图片将被等比例缩小
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="bg-white rounded-xl border p-6 mb-4">
              <div class="font-medium mb-4">转换说明</div>
              <div class="text-sm text-gray-600 space-y-2">
                <p>
                  • <strong>WebP</strong>:
                  现代浏览器支持，压缩率最高，推荐用于网页
                </p>
                <p>• <strong>JPEG</strong>: 兼容性最好，适合照片类图片</p>
                <p>• <strong>PNG</strong>: 支持透明背景，适合图标和截图</p>
                <p>
                  • <strong>AVIF</strong>: 最新格式，压缩率极高，但兼容性有限
                </p>
                <p>• 质量设置会影响文件大小和图片清晰度</p>
                <p>• 尺寸调整可以进一步减小文件大小</p>
              </div>
            </div>
          </TabsContent>
        </template>
      </Transition>
    </Tabs>
  </main>
</template>

<style>
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(20px);
}
.fade-slide-enter-to {
  opacity: 1;
  transform: translateY(0);
}
.fade-slide-leave-from {
  opacity: 1;
  transform: translateY(0);
}
.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}
.queue-fade-enter-active,
.queue-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.queue-fade-enter-from {
  opacity: 0;
  transform: translateX(20px) scale(0.98);
}
.queue-fade-enter-to {
  opacity: 1;
  transform: translateX(0) scale(1);
}
.queue-fade-leave-from {
  opacity: 1;
  transform: translateX(0) scale(1);
}
.queue-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px) scale(0.98);
}
</style>
